import MSEvent
import datetime
import time
import urllib

#time format descriptor used in magic api
TIME_FORMAT_MAGIC = '%d%m%Y_%H%M%S'

class Reader:
    def __init__(self, MSAPIUrl='http://api.car-online.ru'):
        self.MSUrl = MSAPIUrl

    def readURLData(self, request, skey, timerange):
        url = self.MSUrl + '/do?data=%s&skey=%s&begin=%s&end=%s' % (request,
                                                                    skey,
                                                                    timerange[0],
                                                                    timerange[1])
        try:
            print 'DBG: readURLData: reading %s' % url
            f = urllib.urlopen(url)
            d = f.readlines()
            if len(d) == 0:
                return None
            return d
        except Exception, err:
            raise err

    def getToday(self):
        now = datetime.datetime.fromtimestamp(time.time())
        begin   = datetime.datetime(now.year, now.month, now.day, 0,0,0,0)
        end     = begin + datetime.timedelta(days=1)
        return (begin.strftime(TIME_FORMAT_MAGIC), end.strftime(TIME_FORMAT_MAGIC))

    def parseEvent(self, estring):
        s = estring.split('/>')[0]
        s = s.split('<')[1]
        s = s.split(' ')
        e = {}
        for prop in s[1:len(s)]:
            prop = prop.split('=')
            e[prop[0]] = prop[1].replace('"', '')
        return e

    def getEvents(self, obj):
        events = []

        timerange   = self.getToday()
        eventsPGSM  = self.readURLData('events', obj.storage.meta['skey'], timerange)
        if eventsPGSM:
            for s in eventsPGSM:
                try:
                    e = MSEvent.Event()
                    e.fromPGSM(self.parseEvent(s))
                    events.append(e)
                except Exception, err:
                    print 'ERR: getEvents PGSM: ', str(err)
                    continue
        obj.events += events

        eventsCONTACTID = self.readURLData('contactId', obj.storage.meta['skey'], timerange)
        if eventsCONTACTID:
            for s in eventsCONTACTID:
                try:
                    e = MSEvent.Event()
                    e.fromContactId(self.parseEvent(s))
                    events.append(e)
                except Exception, err:
                    print 'ERR: getEvents PGSM: ', str(err)
                    continue
        obj.events += events

        #eventsGPS   = self.readURLData('gpsPoints', obj.storage.meta['skey'], timerange)

##########################
if __name__ == "__main__":
    import sys
    import MSObject

    if len(sys.argv) != 2: print "Usage: %s <storage_root>" % (sys.argv[0])
    g_root = sys.argv[1]

    def case1():
        f1 = MSObject.MSFile.File(g_root, 'test_obj')
        f1.destroy()

        o1 = MSObject.MSObject(g_root, 'test_obj')
        o1.open()
        o1.storage.meta['msId'] = 1
        o1.storage.meta['skey'] = 'a3049a3c320553AC361f668a6bF339' 
        o1.flush()

    def case2():
        o = MSObject.MSObject(g_root, 'test_obj')
        o.open()
        if o.storage.txn != 1: raise RuntimeError('case2: failed 1')
        if o.storage.meta['msId'] != 1: raise RuntimeError('case2: failed 2')

        reader = Reader()
        reader.getEvents(o)

    case1()
    case2()
